#include "AudioEngineWindows.h"
#include <windows.h>
#include <tchar.h>

namespace SypX
{

	std::wstring s2ws(const std::string& s)
	{
		int len;
		int slength = (int)s.length() + 1;
		len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
		wchar_t* buf = new wchar_t[len];
		MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
		std::wstring r(buf);
		delete[] buf;
		return r;
	}

	AudioEngineWindows::AudioEngineWindows(void):existingFile(false)
	{
	}

	AudioEngineWindows::~AudioEngineWindows(void)
	{
		if(existingFile)
		{
			mciSendString(_T("close myFile"), NULL, 0 , 0);
		}

	}

	void AudioEngineWindows::playMusic(const SypX::String& file, bool loop)
	{
		if(existingFile)
		{
			mciSendString(_T("close myFile"), NULL, 0 , 0);
		}
		String command = "open " + file + " alias myFile";
		std::wstring com = s2ws(command);
		mciSendString(com.c_str(), NULL, 0, 0);
		mciSendString(_T("play myFile"), NULL, 0, 0);
		existingFile = true;

	}

	void AudioEngineWindows::stopMusic()
	{
		mciSendString(_T("stop myFile"), NULL, 0, 0);
		mciSendString(_T("seek myFile to start"), NULL, 0, 0);

	}

}